import java.util.concurrent.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 马拉圈
 * Date: 2023-03-24
 * Time: 0:41
 */
public class Test1 {

    public static void main(String[] args) {
        MyBlockingQueue blockingQueue = new MyBlockingQueue(5);
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 25; i++) {
                try {
                    System.out.println("生产1个");
                    blockingQueue.put(1);
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 25; i++) {
                try {
                    blockingQueue.take();
                    System.out.println("消耗1个");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t2.start();
    }



    public static void main2(String[] args) {
        BlockingQueue<Integer> blockingQueue = new LinkedBlockingQueue<>(5);
        Object o = new Object();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 25; i++) {
                try {
                    blockingQueue.put(1);
                    System.out.println("生产1个");
                    Thread.sleep(100);

                    //在这里对局部变量进行加加操作，线程肯定是安全的，以为两个线程修改不同对象

                    //出现生产6个的情况是因为阻塞被唤醒的时候，消耗1个这句话来不及被执行，说到底就是调度原因~
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 25; i++) {
                try {
                    //调度随机，起点不同，所以并不是生产速率成十倍
                    blockingQueue.take();
                    System.out.println("消耗1个");

//两把锁的存在，是可能导致死锁的，即两个线程都进入阻塞~

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        });
        t2.start();
    }



    public static void main1(String[] args) throws InterruptedException {
        //单队列 / 双端队列
        //后续模拟按照其基本功能
        BlockingQueue<String> queue = new ArrayBlockingQueue<>(4);
        queue.put("1. 好耶 ^v^");
        queue.put("2. 好耶 ^v^");
        queue.put("3. 好耶 ^v^");
        queue.put("4. 好耶 ^v^");
        queue.put("5. 好耶 ^v^");
        String result = null;
        result = null;
        result = queue.take();//1
        System.out.println(result);
        result = queue.take();//2
        System.out.println(result);
        result = queue.take();//3
        System.out.println(result);
        result = queue.take();//4
        System.out.println(result);
        result = queue.take();//5
        System.out.println(result);
    }
}
